package com.walkera.wktools.tools;

import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
import android.util.SparseIntArray;

/**
 * 适合短促的 、文件比较小的音效播放
 */
public class SoundPoolTool {
    private SoundPool soundPool;
    private Boolean isLoaded = false;
    private int streamID = 0;
    private SparseIntArray soundData = new SparseIntArray();
    private int currentResouceId;

    /**
     * R.raw.tada
     */
    public void initSoundPool(int[] resourceIds, Context context) {
        soundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
        for (int resourceId : resourceIds) {
            soundData.append(resourceId, soundPool.load(context, resourceId, 1));
        }

        soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool sound, int sampleId, int status) {
                isLoaded = true;
            }
        });
    }

    /**
     * playTimes : 0 播放一次，-1为无限循环，其他值为播放loop+1次
     */
    public void startPlay(int resouceId, int loop, String mode) {
        if (!isLoaded) {
            return;
        }

        if (currentResouceId == resouceId) {
            return;
        }

        if (soundData == null) {
            return;
        }

        currentResouceId = resouceId;
        int soundID = soundData.get(resouceId);
        if (soundID == 0) {
            return;
        }
        // 先停止播放前面的
        stopPlay(false);
        streamID = soundPool.play(soundID, 1, 1, 1, loop, 1);
    }


    public void stopPlay(boolean stopByUser) {
        if (streamID == 0) {
            return;
        }
        soundPool.stop(streamID);
        if (stopByUser) {
            currentResouceId = 0;
        }
    }


    public void release() {
        if (soundData != null) {
            soundData.clear();
            soundData = null;
        }

        if (soundPool != null) {
            if (streamID != 0) {
                soundPool.unload(streamID);
            }
            soundPool.release();
        }

        currentResouceId = 0;
    }


}
